<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Config;
use think\Hook;
use think\Validate;

use think\Session;

use app\admin\library\Auth;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

use think\Log;


use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\IWriter;
//use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;


use fast\Http;
use app\api\controller\Jdycommon;

/**
 * 应该用两个帐号测试，1.案場客戶 仅关联一个案场; colin1 2. 案场列表  外勤(負責地區) mirolu
 */
class Home extends Frontend
{
    protected $layout = 'default';

    protected $noNeedRight = ['*'];

    const ANCHANG_ID = "__homeanchangid__";

    protected $adminuser = null;//关联的admin账号
    protected $groupIds = []; //admin账号关联的角色组fa_auth_group
    protected $isadmin = false;//
    protected $isanchanguser = false; //案場客戶, 仅关联一个案场

    const MOBILE_UUID = "__mobileuuid__";
    protected $uuid = "";//登录用户关联的手机

    public function _initialize()
    {
        parent::_initialize();

        //http://acciot.test/index/home/index?uuid=12345
        if (isset($_GET['uuid'])) {
            $this->uuid = intval($_GET['uuid']);
            Session::set(self::MOBILE_UUID, $this->uuid);
        } else {
            $this->uuid = Session::get(self::MOBILE_UUID);
        }

        $this->adminuser = \app\admin\model\Admin::where('username', $this->auth->username)->find();
        $this->adminuser->uuid = $this->uuid;
        $this->adminuser->save();

        $this->groupIds = [];
        if ($this->adminuser) {
            $agalist = \app\admin\model\AuthGroupAccess::where('uid', $this->adminuser->id)->select();
            foreach ($agalist as $row) {
                $this->groupIds[] = $row->group_id;
            }
        } else {
            //没有关联账号则重新注册
            $user = $this->auth->getUser();
            if ($user) {
                $admin = new \app\admin\model\Admin();
                $admin->username = $user->username;
                $admin->nickname = $user->username;
                $admin->email = $user->email;
                $admin->phone = $user->mobile;
                $admin->salt = $user->salt;
                $admin->password = $user->password;
                $admin->avatar = '/assets/img/avatar.png'; //设置新管理员默认头像。
                $admin->remark = $user->bio;
                $admin->save();
                $this->adminuser = $admin;

                $aga = new \app\admin\model\AuthGroupAccess();
                $aga->uid = $admin->id;
                $aga->group_id = 11;//未開通帳號
                $aga->save();
            }
        }

        if (in_array("2", $this->groupIds) || in_array("1", $this->groupIds)) {
            $this->isadmin = true;//管理员权限不考虑管辖区域
        }

        if (in_array("5", $this->groupIds) || in_array("9", $this->groupIds)) {
            $this->isanchanguser = true;//案場客戶, 仅关联一个案场
        }

        $this->view->assign("isanchanguser", $this->isanchanguser);

        $anchangname = "";
        $anchangid = 0;
        if ($this->isanchanguser) {
            $anchangidlist = json_decode($this->adminuser['anchangids'], TRUE);
            if (count($anchangidlist) > 0) {
                $anchangid = $anchangidlist[0]['id'];
                $anchang = \app\admin\model\jdy\Anchang::get($anchangid);
                if ($anchang) {
                    $anchangname = $anchang->name;
                }
            }
        }

        $this->view->assign("anchangname", $anchangname);
        $this->view->assign("anchangid", $anchangid);
    }

    //获取账号关联的案场list
    public function getanchanglist()
    {
        if ($this->adminuser == null) {
            return;
        }

        $anchangidlist = json_decode($this->adminuser['anchangids'], TRUE);
        $xianshi = [];
        $xianshi[] = $this->adminuser['xianshi1'];
        $xianshi[] = $this->adminuser['xianshi2'];
        $xianshi[] = $this->adminuser['xianshi3'];
        $xianshi[] = $this->adminuser['xianshi4'];
        $xianshi[] = $this->adminuser['xianshi5'];

        $xzq = [];
        $xzq[] = $this->adminuser['xzq1'];
        $xzq[] = $this->adminuser['xzq2'];
        $xzq[] = $this->adminuser['xzq3'];
        $xzq[] = $this->adminuser['xzq4'];
        $xzq[] = $this->adminuser['xzq5'];

        $xianshis = "";//只有市
        $xianshisA = "";
        for ($i = 0; $i < 5; $i++) {
            if (!empty($xianshi[$i]) && empty($xzq[$i])) {
                if (empty($xianshis)) {
                    $xianshis = $xianshi[$i];
                    $xianshisA = "'" . $xianshis . "'";
                } else if (strpos($xianshis, $xianshi[$i]) === false) {
                    $xianshis .= ',' . $xianshi[$i];
                    $xianshisA .= ",'" . $xianshi[$i] . "'";
                }
            }
        }

        $xzqs = "";//
        $xzqsA = "";//
        for ($i = 0; $i < 5; $i++) {
            if (!empty($xzq[$i]) && !empty($xianshi[$i]) && strpos($xianshis, $xianshi[$i]) === false) {
                if (empty($xzqs)) {
                    $xzqs = $xzq[$i];
                    $xzqsA = "'" . $xzqs . "'";
                } else if (strpos($xzqs, $xzq[$i]) === false) {
                    $xzqs .= ',' . $xzq[$i];
                    $xzqsA .= ",'" . $xzq[$i] . "'";
                }
            }
        }

        $whereA = "";
        if (!empty($xianshis)) {
            $whereA = " xianshi in (" . $xianshisA . ") ";
        }

        if (!empty($xzqs)) {
            if (!empty($whereA)) {
                $whereA .= " or ";
            }
            $whereA .= " xzq in (" . $xzqsA . ") ";
        }

        $anchangids = "";//"117,116"
        if ($anchangidlist) {
            foreach ($anchangidlist as $row) {
                if (empty($anchangids)) {
                    $anchangids = $row['id'];
                } else {
                    $anchangids .= ',' . $row['id'];
                }
            }
        }

        if (!empty($anchangids)) {
            if (!empty($whereA)) {
                $whereA .= " or ";
            }
            $whereA .= " id in (" . $anchangids . ") ";
        }

        $list = [];
        if (!empty($whereA)) {
            $list = \app\admin\model\jdy\Anchang::where($whereA)->select();
        }

        return $list;
    }

    public function getanchangids() {
        $anchangidlist = $this->getanchanglist();
        $anchangids = "";
        foreach ($anchangidlist as $row) {
            if (empty($anchangids)) {
                $anchangids = $row['id'];
            } else {
                $anchangids .= ',' . $row['id'];
            }
        }
        return $anchangids;
    }

    /**
     * 首页
     */
    //http://acciot.test/index/home/
    //http://mg.acciot.com.tw/index/home/
    public function index()
    {
        $anchangids = $this->getanchangids();

        if ($this->request->isPost()) {
            $_POST['anchang_id'] = intval($anchangids);
            $_POST['user_id'] = $this->adminuser->id;

            $message = new \app\admin\model\jdy\Message();
            $message->allowField(true)->save($_POST);
            $this->success("新增留言成功！", url('home/index'));
        }

        $datemode = 0;
        if (isset($_GET['datemode'])) {
            $datemode = intval($_GET['datemode']);
        }
        $where1 = "remind_date = '".date("Y-m-d")."'";
        switch ($datemode) {
            default:
                break;
            case 0:
                //今日
                break;
            case 1:
                //最近7天
                $where1 = "remind_date >= '" . date("Y-m-d", strtotime("-7 days", time())) . "' and remind_date <= '" . date("Y-m-d")."'";
                break;
            case 2:
                //最近1個月
                $where1 = "remind_date >= '" . date("Y-m-d", strtotime("-1 month", time())) . "' and remind_date <= '" . date("Y-m-d")."'";
                break;
            case 3:
                //即將到來 -- 未来一周
                $where1 = "remind_date > '" . date("Y-m-d") . "' and remind_date <= '" . date("Y-m-d", strtotime("+7 days", time()))."'";
                break;
        }

        $whereB = "";
        if (!$this->isadmin) {
            if (empty($anchangids)) {
                $whereB = " anchang_id  = 0 ";
            } else {
                $whereB = " anchang_id in (" . $anchangids . ") ";
            }
        }

        $taskList = (new \app\admin\model\jdy\Task)->with(['anchang'])
            ->where($whereB)
            ->where($where1)
            ->select();
        $taskList = collection($taskList)->toArray();

        $weekarray = array("日", "一", "二", "三", "四", "五", "六");

        foreach ($taskList as &$row) {
            $a = date("w", strtotime($row['remind_date']));
            $row['weekinfo'] =  "星期" . $weekarray[$a];
        }


        $this->view->assign("taskList", $taskList);
        $this->view->assign("title", "首页");

        $paomadeng = "";
        $where1 = "";
        if ($this->isanchanguser) {
            $where1 = " viewer_type <> '恆銓人員' ";
        } else {
            $where1 = " viewer_type <> '客戶' ";
        }
        $marqueelist = \app\admin\model\jdy\Marquee::where("launch", 1)
            ->where("start_date", "<", date("Y-m-d H:i:s"))
            ->where("end_date", ">", date("Y-m-d H:i:s"))
            ->where($where1)
            ->select();

        foreach ($marqueelist as $row0) {
            $paomadeng .= $row0['message'] . "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
        }

        if (empty($paomadeng)) {
            $paomadeng = "跑马灯...  ... ";
        }

        $this->view->assign("paomadeng", $paomadeng);

        return $this->view->fetch();
    }

    /**
     * 最新消息
     */
    public function news()
    {
        $anchangids = $this->getanchangids();
        $whereA = " anchang_id in (" . $anchangids . ") ";
        $newslist = \app\admin\model\jdy\News::where($whereA)->order('id', 'DESC')->limit(200)->select();
        if ($newslist) {
            $newslist = collection($newslist)->toArray();
        }

        $this->view->assign("newslist", $newslist);
        $this->view->assign("title", "最新消息");
        return $this->view->fetch();
    }

    /**
     * 案场信息
     */
    //http://acciot.test/index/home/anchanginfo
    public function anchanginfo()
    {
        $anchangid = 0;
        if (isset($_GET['anchang_id'])) {
            $anchangid = intval($_GET['anchang_id']);
        } else {
            $this->error("错误的案场！");
        }
        $anchang = \app\admin\model\jdy\Anchang::get($anchangid)->toArray();

        $this->view->assign("anchang", $anchang);
        $this->view->assign("title", "案场信息");
        return $this->view->fetch();
    }

    /**
     * 留言歷史
     */
    //http://acciot.test/index/home/lyls
    public function lyls()
    {
        $anchangid = 0;
        if (isset($_GET['anchang_id'])) {
            $anchangid = intval($_GET['anchang_id']);
        } else {
            $this->error("错误的案场！");
        }
        $msglist = \app\admin\model\jdy\Message::where("anchang_id", $anchangid)->order("id", "desc")->select();

        $msglist = collection($msglist)->toArray();
        foreach ($msglist as &$row) {
            $row['user'] = $this->getadminnickname($row['user_id']);
            $row['hcuser'] = $this->getadminnickname($row['hcuser_id']);
        }

        $this->view->assign("msglist", $msglist);
        $this->view->assign("title", "留言歷史");
        return $this->view->fetch();
    }

    function getadminnickname($adminid)
    {
        $admin = \app\admin\model\Admin::get($adminid);
        if ($admin) {
            return $admin->nickname;
        }

        return "";
    }

    /**
     * 添加維修紀錄 无关联taskid；由案场列表进入
     */
    //http://acciot.test/index/home/addmaintenance?anchang_id=3
    public function addmaintenance()
    {
        $anchangid = 0;
        if (isset($_GET['anchang_id'])) {
            $anchangid = intval($_GET['anchang_id']);
        } else {
            $this->error("错误的案场！");
        }

        $mode = -1;
        if (isset($_GET['mode'])) {
            $mode = intval($_GET['mode']);
        }
        $anchang = \app\admin\model\jdy\Anchang::get($anchangid)->toArray();

        $keywords = "";
        if (isset($_GET['keywords'])) {
            $keywords = $_GET['keywords'];
        }

        if ($this->request->isPost()) {

            if (isset($_POST['keywords'])) {
                $this->success("查询維修紀錄成功！", url('home/addmaintenance')."?anchang_id={$_POST['anchang_id']}&keywords=".$_POST['keywords']);
            }

            $params = $this->request->post("row/a");
            if ($params) {
                $result = false;
                Db::startTrans();
                try {

                    if ($this->isanchanguser) {
                        $params['user_id'] = $this->adminuser->id;
                        $model = new \app\admin\model\jdy\Message();
                        $result = $model->allowField(true)->save($params);
                    } else {
                        $params['luruman'] = $this->adminuser->nickname;
                        $params['anchang_id'] = $anchangid;
                        $model = new \app\admin\model\jdy\Maintenance;
                        $result = $model->allowField(true)->save($params);
                    }

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $url = urldecode($params['url']);
                if ($result !== false) {
                    $this->success("添加維修紀錄成功！", $url ? $url : url('home/anchanglist'));
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("anchang", $anchang);
        //添加维修记录的逻辑？使用上一次task的id？
        $this->view->assign("content0", $this->getcontent0($anchangid, $mode, $keywords));//设置taskid
        $this->view->assign("content1", date("Y-m-d") . " " . $this->adminuser->nickname . ":\n");

        if ($this->isanchanguser) {
            $this->view->assign("title", "維修紀錄");
        } else {
            $this->view->assign("title", "添加維修紀錄");
        }
        $this->view->assign("keywords", $keywords);
        
        $url = "";
        if (isset($_SERVER["HTTP_REFERER"])) {
            $url = urlencode($_SERVER["HTTP_REFERER"]);
        }
        $this->view->assign("url", $url);
        return $this->view->fetch();
    }


    /**
     * 案場信息
     */
    //http://acciot.test/index/home/anchang
    public function anchang()
    {
        $anchangid = 0;
        if (isset($_GET['anchang_id'])) {
            $anchangid = intval($_GET['anchang_id']);
        } else {
            $this->error("错误的案场！");
        }

        $anchang = \app\admin\model\jdy\Anchang::get($anchangid)->toArray();

        $heyue = \app\admin\model\jdy\Heyue::where("anchang_id", $anchangid)->order('id', 'DESC')->limit(1)->find();

        if ($heyue) {
            $heyue = $heyue->toArray();

            if ($heyue['service_hours'] == 0) {
                $heyue['service_hoursinfo'] = "AM：09:30~PM12:30 或 PM13:30~PM17:00";
            } else {
                $heyue['service_hoursinfo'] = "AM：09:30~PM12:30 及 PM13:30~PM17:00";
            }
        }

        $this->view->assign("anchang", $anchang);
        $this->view->assign("heyue", $heyue);
        $this->view->assign("title", "案場信息");
        return $this->view->fetch();
    }

    //維修歷史紀錄
    //http://acciot.test/index/home/maintenancelog
    public function maintenancelog()
    {
        $keywords = "";
        if (isset($_GET['keywords'])) {
            $keywords = $_GET['keywords'];
        }

        if ($this->request->isPost()) {
            if (isset($_POST['keywords'])) {
                $this->success("查询維修紀錄成功！", url('home/maintenancelog') . "?ids={$_POST['task_id']}&keywords=" . $_POST['keywords'], '', 1);
            }
        }

        $task_id = 0;
        if (isset($_GET['ids'])) {
            $task_id = $_GET['ids'];
        } else {
            $this->error("错误的案场！");
        }

        $task = \app\admin\model\jdy\Task::get($task_id);
        $anchangid = 0;
        if ($task) {
            $anchangid = $task->anchang_id;
        }

        $anchang = \app\admin\model\jdy\Anchang::get($anchangid)->toArray();

        $this->view->assign("anchang", $anchang);
        $this->view->assign("task_id", $task_id);
        $this->view->assign("content0", $this->getcontent0($anchangid, -1, $keywords));
        $this->view->assign("keywords", $keywords);

        $this->view->assign("title", "維修歷史紀錄");
        return $this->view->fetch();
    }

    //調整工作提醒
    //http://acciot.test/index/home/updatetask
    public function updatetask()
    {
        if ($this->request->isPost()) {
            $taskid = $_POST['taskid'];
            $task = \app\admin\model\jdy\Task::get($taskid);
            if ($task) {
                if ($task->images != $_POST['images']) {
                    $_POST['content'] .= " [增加工作圖片]";
                }
                //[標題: 標題] [提醒日期: 日期] [提醒狀態: 狀態] [內容: 內容]
                $content = "[標題: {$task['title']}][提醒日期: {$_POST['remind_date']}][提醒狀態: {$_POST['task_status']}][內容: {$_POST['content']}]";

                $task->luruman = $this->adminuser->nickname;
                $task->remind_date = $_POST['remind_date'];
                $task->remind_type = $_POST['remind_type'];
                $task->task_status = $_POST['task_status'];
                $task->images = $_POST['images'];
                $task->save();

                $params = [];
                $params['luruman'] = $this->adminuser->nickname;
                $params['anchang_id'] = $task->anchang_id;
                $params['task_id'] = $task->id;
                $params['content'] = $content;
                $params['images'] = $_POST['images'];
                $model = new \app\admin\model\jdy\Maintenance;
                $result = $model->allowField(true)->save($params);
                
            }

            $this->success("新增工作提醒成功！", url('home/task') . "?ids=" . $taskid);
        }

        $ids = 0;
        if (isset($_GET['ids'])) {
            $ids = $_GET['ids'];
        }

        $task = \app\admin\model\jdy\Task::get($ids);

        $this->view->assign("remindTypeList", $task->getRemindTypeList());
        $this->view->assign("taskStatusList", $task->getTaskStatusList());

        if ($task) {
            $task = $task->toArray();
            $task['anchang'] = \app\admin\model\jdy\Anchang::get($task['anchang_id'])->toArray();
        }

        $this->view->assign("task", $task);
        $this->view->assign("content0", $this->getcontent1($task['anchang_id'], $task['id']));
        $this->view->assign("content1", date("Y-m-d") . " " . $this->adminuser->nickname . " ");
        $this->view->assign("title", "調整工作提醒");
        $this->view->assign("anchang_id", $task['anchang_id']);

        return $this->view->fetch();
    }

    //新增工作提醒
    //http://acciot.test/index/home/newtask
    public function newtask()
    {
        if ($this->request->isPost()) {
            $_POST['luruman'] = $this->adminuser->nickname;
            $_POST['maintenanceuser_id'] = $this->adminuser->id;

            $task = new \app\admin\model\jdy\Task();
            $result = $task->allowField(true)->save($_POST);

            $_POST['task_id'] = $task->id;
            $model = new \app\admin\model\jdy\Maintenance;
//            新增工作事項 [標題: 標題] [提醒日期: 日期] [提醒狀態: 狀態] [內容: 內容]
            $_POST['content'] = "新增工作事項 [標題: {$task->title}] [提醒日期: {$task->remind_date}] [提醒狀態: {$task->task_status}] [內容: {$_POST['content']}]";
            $result = $model->allowField(true)->save($_POST);

            $this->success("新增工作提醒成功！", url('home/anchanglist'));
        }


        $anchang_id = 0;
        if (isset($_GET['anchang_id'])) {
            $anchang_id = $_GET['anchang_id'];
        }

        $anchangname = "";
        $anchang = \app\admin\model\jdy\Anchang::get($anchang_id);
        if ($anchang) {
            $anchangname = $anchang->name;
        }

        $task = new \app\admin\model\jdy\Task();

        $this->view->assign("remindTypeList", $task->getRemindTypeList());
        $this->view->assign("taskStatusList", $task->getTaskStatusList());
        $this->view->assign("anchang_id", $anchang_id);
        $this->view->assign("anchangname", $anchangname);
        $this->view->assign("title", "新增工作提醒");

        $handleuser_id = 0;
        $this->view->assign("handleuser_id", $handleuser_id);
        $this->view->assign("maintenanceuser_id", $this->adminuser->id);
        $this->view->assign("maintenanceuser", $this->adminuser->nickname);

        //知會人員 案场关联的
        $Jdycommon = new Jdycommon();
        $list2 = $Jdycommon->getnotifyusers($anchang);
        $notifyusers = "";
        foreach ($list2 as $row) {
            $notifyusers .= $row['name'] . ",";
        }
        $this->view->assign("notifyusers", $notifyusers);

        //指定處理人員
        $list3 = $Jdycommon->gethandleusers($anchang);
        $this->view->assign("handleuserList", $list3);

        return $this->view->fetch();
    }

    /**
     * 案场列表
     */
    //http://acciot.test/index/home/anchanglist
    public function anchanglist()
    {
        if ($this->request->isPost()) {

            $name = $this->request->post('name', '');
            $xianshi = $this->request->post('xianshi', '');
            $xzq = $this->request->post('xzq', '');
            $url = url('home/anchanglist')."?name={$name}&xianshi={$xianshi}&xzq={$xzq}";
            $this->success(__('查询成功！'), $url);
        }

        $whereA = "";
        $name = $this->request->request('name', "");
        if (!$name) {
            $name = '';
        }
        $xianshi = $this->request->request('xianshi', "");
        if (!$xianshi) {
            $xianshi = '';
        }
        $xzq = $this->request->request('xzq', "");
        if (!$xzq) {
            $xzq = '';
        }

        $this->view->assign("name", $name);
        $this->view->assign("xianshi", $xianshi);
        $this->view->assign("xzq", $xzq);

        if (!empty($name)) {
            $whereA .= " name like '%" . $name . "%'";
        }
        if (!empty($xianshi)) {
            if (!empty($whereA)) {
                $whereA .= " and ";
            }
            $whereA .= " xianshi = '" . $xianshi . "'";
        }
        if (!empty($xzq)) {
            if (!empty($whereA)) {
                $whereA .= " and ";
            }
            $whereA .= " xzq = '" . $xzq . "'";
        }

        $anchangids = $this->getanchangids();
        $whereB = "";
        if (!$this->isadmin) {
            if (empty($anchangids)) {
                $whereB = " id  = 0 ";
            } else {
                $whereB = " id in (" . $anchangids . ") ";
            }
        }

        $anchanglist = \app\admin\model\jdy\Anchang::where($whereA)
            ->where($whereB)
            ->select();

        $anchanglist = collection($anchanglist)->toArray();
        $anchanglist2 = [];
        $adminid = $this->adminuser->id;
        $i = 0;
        foreach ($anchanglist as &$row) {
            $tasklist = collection(\app\admin\model\jdy\Task::where('anchang_id', $row['id'])->order("id", "desc")->limit(3)->select())->toArray();
            $row['tasklist'] = $tasklist;

            //for 测试
//            if (count($tasklist) > 0) {
//                $anchanglist2[] = $row;
//            }
            $row['index'] = $i;//排序  有掛在公司窗口，希望優先排序
            if ($adminid == $row['companywindow_id']) {
                $row['index'] += 100000;
            }
            $i++;
        }

        //排序
        $idArr = array_column($anchanglist, 'index');
        array_multisort($idArr, SORT_DESC, $anchanglist);

        $this->view->assign("anchanglist", $anchanglist);
        $this->view->assign("title", "案场列表");
        return $this->view->fetch();
    }

    public function searchanchang()
    {
        if ($this->request->isPost()) {

            $name = $this->request->post('name', '');
            $xianshi = $this->request->post('xianshi', '');
            $xzq = $this->request->post('xzq', '');
            $url = url('home/searchanchang')."?name={$name}&xianshi={$xianshi}&xzq={$xzq}";
            $this->success(__('查询成功！'), $url);
        }

        $whereA = "";
        $name = $this->request->request('name', "");
        if (!$name) {
            $name = '';
        }
        $xianshi = $this->request->request('xianshi', "");
        if (!$xianshi) {
            $xianshi = '';
        }
        $xzq = $this->request->request('xzq', "");
        if (!$xzq) {
            $xzq = '';
        }

        $this->view->assign("name", $name);
        $this->view->assign("xianshi", $xianshi);
        $this->view->assign("xzq", $xzq);

        if (!empty($name)) {
            $whereA .= " name like '%" . $name . "%'";
        }
        if (!empty($xianshi)) {
            if (!empty($whereA)) {
                $whereA .= " and ";
            }
            $whereA .= " xianshi = '" . $xianshi . "'";
        }
        if (!empty($xzq)) {
            if (!empty($whereA)) {
                $whereA .= " and ";
            }
            $whereA .= " xzq = '" . $xzq . "'";
        }

        $anchangids = $this->getanchangids();
        $whereB = "";
        if (!$this->isadmin) {
            if (empty($anchangids)) {
                $whereB = " id  = 0 ";
            } else {
                $whereB = " id in (" . $anchangids . ") ";
            }
        }

        $anchanglist = \app\admin\model\jdy\Anchang::where($whereA)
            ->where($whereB)
            ->select();

        $anchanglist = collection($anchanglist)->toArray();
        $anchanglist2 = [];
        foreach ($anchanglist as &$row) {
            $tasklist = collection(\app\admin\model\jdy\Task::where('anchang_id', $row['id'])->select())->toArray();
            $row['tasklist'] = $tasklist;

            //for 测试
//            if (count($tasklist) > 0) {
//                $anchanglist2[] = $row;
//            }
        }

        $this->view->assign("anchanglist", $anchanglist);
        $this->view->assign("title", "切換案場");
        return $this->view->fetch();
    }

    /**
     * 水電表
     */
    //http://acciot.test/index/home/sdb
    public function sdb()
    {
        $anchang_id = 0;
        if (isset($_GET['anchang_id'])) {
            $anchang_id = intval($_GET['anchang_id']);
        }

        $model = new \app\admin\model\jdy\Sdbiao();
        $sdblist = $model
            ->with(['anchang','sdtype'])
            ->where('anchang_id', $anchang_id)
            ->select();

        $sdblist = collection($sdblist)->toArray();
        foreach ($sdblist as &$row) {
            $row['logdate'] = "--";
            $row['cbs'] = "无记录";
            $sdbloglist = \app\admin\model\jdy\Sdblog::where('sdbiao_id', $row['id'])->order("id desc")->select();
            $num = 0;
            $row['lastcbs'] = 0;
            $row['pinjun'] = 0;
            $cbsstart = 0; //原始表记录
            foreach ($sdbloglist as $row0) {
                if ($num == 0) {
                    $row['logdate'] = $row0->create_time;
                    $row['cbs'] = $row0->cbs;
                } else if ($num == 1) {
                    $row['lastcbs'] = $row0->cbs;
                }
                $cbsstart = $row0->cbs;
                $num++;
            }
            if ($num > 1) {
                $row['pinjun'] = ($row['cbs'] - $cbsstart) / ($num - 1);
            }
        }

        $this->view->assign("sdblist", $sdblist);
        $this->view->assign("title", "水電表");

        return $this->view->fetch();
    }

    /**
     * 抄表作業
     */
    //http://acciot.test/index/home/cbzy
    public function cbzy()
    {
        $anchang_id = 0;
        if (isset($_GET['anchang_id'])) {
            $anchang_id = intval($_GET['anchang_id']);
            Session::set(self::ANCHANG_ID, $anchang_id);
        } else {
            $anchang_id = Session::get(self::ANCHANG_ID);
            if (empty($anchang_id)) {
                $anchangids = $this->getanchangids();
                if ($anchangids) {
                    $anchanglist = explode(',', $anchangids);
                    if (count($anchanglist) > 0) {
                        $anchang_id = $anchanglist[0];
                        Session::set(self::ANCHANG_ID, $anchang_id);
                    }
                }
            }
        }

        $sdtype_id = 0;
        if (isset($_GET['sdtype_id'])) {
            $sdtype_id = intval($_GET['sdtype_id']);
        }

        if ($this->request->isPost()) {
            $this->success("類型選擇！", url('home/cbzy')."?anchang_id=".$_POST['anchang_id']."&sdtype_id=".$_POST['sdtype_id']);
        }

        $anchang = \app\admin\model\jdy\Anchang::get($anchang_id);

        $model = new \app\admin\model\jdy\Sdbiao();
        if ($sdtype_id > 0) {
            $sdblist = $model
                ->with(['anchang', 'sdtype'])
                ->where('anchang_id', $anchang_id)
                ->where('sdtype_id', $sdtype_id)
                ->select();
        } else {
            $sdblist = $model
                ->with(['anchang', 'sdtype'])
                ->where('anchang_id', $anchang_id)
                ->select();
        }

        $sdblist = collection($sdblist)->toArray();
        foreach ($sdblist as &$row) {
            $row['logdate'] = "--";
            $row['cbs'] = "无记录";
            $Sdblog = \app\admin\model\jdy\Sdblog::where('sdbiao_id', $row['id'])->order("id desc")->limit(1)->find();
            if ($Sdblog) {
                $row['logdate'] = $Sdblog->create_time;
                $row['cbs'] = $Sdblog->cbs;
            }
        }

        $this->view->assign("anchangname", $anchang->name);
        $this->view->assign("anchang_id", $anchang_id);
        $this->view->assign("sdblist", $sdblist);
        $sdtypelist = collection(\app\admin\model\jdy\Sdtype::all())->toArray();
        $this->view->assign("sdtypelist", $sdtypelist);
        $this->assignconfig('anchang_id', $anchang_id);

        $this->view->assign("sdtype_id", $sdtype_id);
        $this->view->assign("title", "抄表作業");
        return $this->view->fetch();
    }

    //新增电表
    public function cbzy1()
    {
        if ($this->request->isPost()) {
            $Sdbiao = new \app\admin\model\jdy\Sdbiao();
            $Sdbiao->sdtype_id = $_POST['sdtype_id'];
            $Sdbiao->anchang_id = $_POST['anchang_id'];
            $Sdbiao->name = $_POST['name'];
            $Sdbiao->biaohao = $_POST['biaohao'];
            $Sdbiao->images = $_POST['images'];
            $Sdbiao->save();

            $sdtype = \app\admin\model\jdy\Sdtype::get($_POST['sdtype_id']);
            $sdtypename = "";
            if ($sdtype) {
                $sdtypename = $sdtype->name;
            }

            $now = date("Y-m-d", time());
            $maintenance = new \app\admin\model\jdy\Maintenance;
            $maintenance->anchang_id = $_POST['anchang_id'];
            $maintenance->content = "{$now} {$this->adminuser->nickname} 新增[類型:{$sdtypename}][名稱:{$_POST['name']}][表號:{$_POST['biaohao']}]";
            $maintenance->luruman = $this->adminuser->nickname;
            $maintenance->save();

            $this->success("新增電表成功！", url('home/cbzy'));
        }

        $anchang_id = 0;
        if (isset($_GET['anchang_id'])) {
            $anchang_id = intval($_GET['anchang_id']);
            Session::set(self::ANCHANG_ID, $anchang_id);
        } else {
            $anchang_id = Session::get(self::ANCHANG_ID);
            if (empty($anchang_id)) {
                $anchangids = $this->getanchangids();
                if ($anchangids) {
                    $anchanglist = explode(',', $anchangids);
                    if (count($anchanglist) > 0) {
                        $anchang_id = $anchanglist[0];
                        Session::set(self::ANCHANG_ID, $anchang_id);
                    }
                }
            }
        }

        $anchang = \app\admin\model\jdy\Anchang::get($anchang_id);
        $this->view->assign("anchangname", $anchang->name);
        $this->view->assign("anchang_id", $anchang_id);

        $sdtypelist = \app\admin\model\jdy\Sdtype::all();
        $sdtypelist = collection($sdtypelist)->toArray();
        $this->view->assign("sdtypelist", $sdtypelist);

        $this->view->assign("title", "新增電表");
        return $this->view->fetch();
    }

    //新增抄表记录
    public function cbzy2()
    {
        if ($this->request->isPost()) {

            $lastcbs = 0;//上次抄表数
            $Sdblog = \app\admin\model\jdy\Sdblog::where('sdbiao_id', $_POST['sdbiao_id'])->order("id desc")->limit(1)->find();
            if ($Sdblog) {
                $lastcbs = intval($Sdblog->cbs);
            }

            $Sdblog = new \app\admin\model\jdy\Sdblog();
            $Sdblog->cbs = $_POST['cbs'];
            $Sdblog->sdbiao_id = $_POST['sdbiao_id'];
            $Sdblog->save();

            $cbsX = intval($_POST['cbs']) - $lastcbs;
            $sdb = \app\admin\model\jdy\Sdbiao::get($_POST['sdbiao_id']);

            if ($sdb) {
                $sdbtype = \app\admin\model\jdy\Sdtype::get($sdb->sdtype_id);

                $now = date("Y-m-d", time());
                $maintenance = new \app\admin\model\jdy\Maintenance;
                $maintenance->anchang_id = $sdb->anchang_id;
                //新增紀錄 [類型] [表名稱] [表號] [本次數值]: [差異值]
                $maintenance->content = "{$now} {$this->adminuser->nickname} 新增紀錄 [{$sdbtype->name}] [{$sdb->name}] [{$sdb->biaohao}] [本次數值：{$_POST['cbs']}]: [差異值：{$cbsX}]";
                $maintenance->luruman = $this->adminuser->nickname;
                $maintenance->save();
            }
            
            $this->success("新增抄表记录成功！", url('home/cbzy'));
        }

        $ids = 0;
        if (isset($_GET['ids'])) {
            $ids = $_GET['ids'];//fa_jdy_sdbiao id
        }

        $sdbiao = \app\admin\model\jdy\Sdbiao::get($ids);

        $anchangname = "";
        $anchang_id = 0;
        $sdtypename = "";
        if ($sdbiao) {
            $anchang = \app\admin\model\jdy\Anchang::get($sdbiao->anchang_id);
            if ($anchang) {
                $anchangname = $anchang->name;
                $anchang_id = $sdbiao->anchang_id;
            }

            $sdtype = \app\admin\model\jdy\Sdtype::get($sdbiao->sdtype_id);
            if ($sdtype) {
                $sdtypename = $sdtype->name;
            }
        }

        $sdbiao = $sdbiao->toArray();
        $sdbiao['sdtypename'] = $sdtypename;
        $sdbiao['cbs'] = "";
        $sdbiao['logdate'] = "";
        $sdbiao['qlccz'] = "";

        $Sdblog = \app\admin\model\jdy\Sdblog::where('sdbiao_id', $sdbiao['id'])->order("id desc")->limit(2)->select();
        $i = 0;
        foreach ($Sdblog as $row) {
            if ($i > 0) {
                $sdbiao['qlccz'] = intval($sdbiao['cbs']) - intval($row->cbs);
                break;
            } else {
                $sdbiao['logdate'] = $row->create_time;
                $sdbiao['cbs'] = $row->cbs;
            }
            $i++;
        }


        $this->view->assign("anchangname", $anchangname);
        $this->view->assign("anchang_id", $anchang_id);
        $this->view->assign("sdbiao", $sdbiao);

        $imageslist = explode(",", $sdbiao['images']);
        $this->view->assign("imageslist", $imageslist);

        $this->view->assign("title", "抄表作業-新增紀錄");
        return $this->view->fetch();
    }

    //抄表记录确认
    public function cbqr()
    {
        if ($this->request->isPost()) {

            $lastcbs = 0;//上次抄表数
            $Sdblog = \app\admin\model\jdy\Sdblog::where('sdbiao_id', $_POST['sdbiao_id'])->order("id desc")->limit(1)->find();
            if ($Sdblog) {
                $lastcbs = intval($Sdblog->cbs);
            }

            $Sdblog = new \app\admin\model\jdy\Sdblog();
            $Sdblog->cbs = $_POST['cbs'];
            $Sdblog->sdbiao_id = $_POST['sdbiao_id'];
            $Sdblog->save();

            $cbsX = intval($_POST['cbs']) - $lastcbs;
            $sdb = \app\admin\model\jdy\Sdbiao::get($_POST['sdbiao_id']);

            if ($sdb) {
                $sdbtype = \app\admin\model\jdy\Sdtype::get($sdb->sdtype_id);

                $now = date("Y-m-d", time());
                $maintenance = new \app\admin\model\jdy\Maintenance;
                $maintenance->anchang_id = $sdb->anchang_id;
                //新增紀錄 [類型] [表名稱] [表號] [本次數值]: [差異值]
                $maintenance->content = "{$now} {$this->adminuser->nickname} 新增紀錄 [{$sdbtype->name}] [{$sdb->name}] [{$sdb->biaohao}] [本次數值：{$_POST['cbs']}]: [差異值：{$cbsX}]";
                $maintenance->luruman = $this->adminuser->nickname;
                $maintenance->save();
            }

            $this->success("新增抄表记录成功！", url('home/cbzy'));
        }

        $sdbiao_id = 0;
        $cbs = 0;
        if (isset($_GET['sdbiao_id'])) {
            $sdbiao_id = $_GET['sdbiao_id'];
        }
        if (isset($_GET['cbs'])) {
            $cbs = $_GET['cbs'];
        }

        $sdbiao = \app\admin\model\jdy\Sdbiao::get($sdbiao_id);
        $sdbiao = $sdbiao->toArray();
        $sdbiao['cbs'] = "";
        $sdbiao['logdate'] = "";
        $sdbiao['qlccz'] = "";

        $Sdblog = \app\admin\model\jdy\Sdblog::where('sdbiao_id', $sdbiao['id'])->order("id desc")->limit(2)->select();
        $i = 0;
        foreach ($Sdblog as $row) {
            if ($i > 0) {
                $sdbiao['qlccz'] = intval($sdbiao['cbs']) - intval($row->cbs);
                break;
            } else {
                $sdbiao['logdate'] = $row->create_time;
                $sdbiao['cbs'] = $row->cbs;
            }
            $i++;
        }

        $this->view->assign("sdbiao_id", $sdbiao_id);
        $this->view->assign("cbs", $cbs);
        $this->view->assign("sdbiao", $sdbiao);
        $this->view->assign("title", "抄表记录确认");
        return $this->view->fetch();
    }

    /**
     * IOT裝置
     */
    //http://acciot.test/index/home/iot
    public function iot()
    {
        if ($this->request->isPost()) {
            $anchangid = $_POST['anchang_id'];
            $keyword = $_POST['keyword'];
            $smallcategory_id = $_POST['smallcategory_id'];;
            $url = url('home/iot') . "?anchang_id={$anchangid}&keyword={$keyword}&smallcategory_id={$smallcategory_id}";
            $this->success(__('查询成功！'), $url);
        }

        $anchangid = 0;
        if (isset($_GET['anchang_id'])) {
            $anchangid = intval($_GET['anchang_id']);
        }
        $keyword = "";
        if (isset($_GET['keyword'])) {
            $keyword = $_GET['keyword'];
        }
        $smallcategory_id = 0;
        if (isset($_GET['smallcategory_id'])) {
            $smallcategory_id = intval($_GET['smallcategory_id']);
        }

        $room_id = 0;
        $anchang = \app\admin\model\jdy\Anchang::get($anchangid);
        if ($anchang) {
            $room_id = $anchang->room_id;
            $anchangname = $anchang->name;
        }

        $model = new \app\admin\model\jdy\Device();
        $where = "";
        if (!empty($keyword)) {
            $where = " (device.name like '%" . $keyword . "%'";
            $where .= " or selfname like '%" . $keyword . "%'";
            $where .= " or deviceid like '%" . $keyword . "%' )";
        }

        $smallcategoryname = "";
        if ($smallcategory_id > 0) {
            if (!empty($where)) {
                $where .= " and ";
            }
            $where .= " smallcategory_id = " . $smallcategory_id;

            $smallcategory = \app\admin\model\jdy\Smallcategory::get($smallcategory_id);
            if ($smallcategory) {
                $smallcategoryname = $smallcategory['name'];
            }
        }

        $smallcategorylist = \app\admin\model\jdy\Smallcategory::where('bigcategory_id', '<>', '4')->select();
        $smallcategorylist = collection($smallcategorylist)->toArray();

        $this->view->assign("smallcategoryname", $smallcategoryname);
        $this->view->assign("smallcategory_id", $smallcategory_id);
        $this->view->assign("smallcategorylist", $smallcategorylist);

        $list = $model
            ->with(['room', 'smallcategory'])
            ->where($where)
            ->where('room_id', $room_id)
            ->select();

        $iotlist = collection($list)->toArray();
        foreach ($iotlist as &$row) {
            $row['onlinestr'] = '離線';
            if (intval($row['online']) == 1) {
                $row['onlinestr'] = '在線';
            }
            $t = time() - intval($row['online_starttime']);
            $h = intval($t / 3600);
            $m = intval(($t - $h * 3600) / 60);
            $s = intval($t - $h * 3600 - $m * 60);
            $row['online_time'] = $h . ":" . $m . ":" . $s;
        }

        $this->view->assign("iotlist", $iotlist);
        $this->view->assign("keyword", $keyword);
        $this->view->assign("anchangname", $anchangname);
        $this->view->assign("anchang_id", $anchangid);
        $this->view->assign("title", "IOT裝置");
        return $this->view->fetch();
    }

    /**
     * 工作事項
     */
    //http://acciot.test/index/home/task
    public function task()
    {
        $ids = 0;
        if (isset($_GET['ids'])) {
            $ids = $_GET['ids'];
        }

        $task = \app\admin\model\jdy\Task::get($ids);

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $result = false;
                Db::startTrans();
                try {
                    if (!$task) {
                        $this->error(__('错误的工作事項！'));
                    }
                    $params['luruman'] = $this->adminuser->nickname;
                    $params['task_id'] = $ids;
                    $params['anchang_id'] = $task['anchang_id'];
                    $model = new \app\admin\model\jdy\Maintenance;

                    if ($task->images != $params['images']) {
                        $params['content'] .= " [增加工作圖片]";
                    }
                    //[標題: 標題] [提醒日期: 日期] [提醒狀態: 狀態] [內容: 內容]
                    //提醒日期？？没有呀
                    $params['content'] = "[標題: {$task['title']}][內容: {$params['content']}]";

                    $task->images =  $params['images'];
                    $task->save();

                    $result = $model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success("添加維修紀錄成功！");//, url('home/index')
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        if ($task) {
            $task = $task->toArray();
            $task['anchang'] = \app\admin\model\jdy\Anchang::get($task['anchang_id'])->toArray();
        }

        $kssg = "開始施工";
        if ($task['task_status'] == "未完工") {
            $kssg = "正在施工";
        }

        $this->view->assign("kssg", $kssg);
        $this->view->assign("task", $task);
        $this->view->assign("content0", $this->getcontent1($task['anchang_id'], $task['id']));
        $this->view->assign("content1", date("Y-m-d") . " " . $this->adminuser->nickname . " ");
        $this->view->assign("title", "工作事項");
        $this->view->assign("anchang_id", $task['anchang_id']);
        $this->assignconfig('task_id', $task['id']);

        return $this->view->fetch();
    }

    /**
     * tasklist for anchang
     */
    //http://acciot.test/index/home/tasklist?anchang_id=11
    public function tasklist()
    {
        $anchang_id = 0;
        if (isset($_GET['anchang_id'])) {
            $anchang_id = $_GET['anchang_id'];
        }

        $anchang = \app\admin\model\jdy\Anchang::get($anchang_id);
        $anchangname = "";
        if ($anchang) {
            $anchangname = $anchang->name;
        }

        $tasklist = \app\admin\model\jdy\Task::with(['anchang'])
            ->where('anchang_id', $anchang_id)
            ->select();

        $tasklist = collection($tasklist)->toArray();

        $weekarray = array("日", "一", "二", "三", "四", "五", "六");

        foreach ($tasklist as &$row) {
            $a = date("w", strtotime($row['remind_date']));
            $row['weekinfo'] =  "星期" . $weekarray[$a];
        }

        $this->view->assign("tasklist", $tasklist);
        $this->view->assign("title", "工作事項列表");
        $this->view->assign("anchang_id", $anchang_id);
        $this->assignconfig('anchang_id', $anchang_id);
        $this->view->assign("anchangname", $anchangname);

        return $this->view->fetch();
    }

    /**
     * 施工完毕
     */
    //http://acciot.test/index/home/sgwb
    public function sgwb() {
        $ids = 0;
        if (isset($_GET['ids'])) {
            $ids = $_GET['ids'];
        }

        $task = \app\admin\model\jdy\Task::get($ids);
        $this->view->assign("task", $task);
        $this->view->assign("title", "施工完毕");
        $this->assignconfig('task_id', $task['id']);
        return $this->view->fetch();
    }

    function getcontent1($anchang_id, $task_id)
    {
        $model = new \app\admin\model\jdy\Maintenance;
        $content0 = "";
        $list = $model
            ->where('anchang_id', $anchang_id)
            ->where('task_id', $task_id)
            ->field('content, message, switch, create_time, luruman')
            ->order("create_time desc")
            ->select();

        foreach ($list as $row) {
            $message = "";
            if ($row->message) {
                $message = $row->message;
            }

            $content0 .= $row->create_time . "\n录入人員:" .$row->luruman. "\n内容:" . $row->content . "\n主管留言:" . $message . "\n\n";
        }

        return $content0;
    }

    function getcontent0($anchang_id, $mode = -1, $keywords="")
    {
        $model = new \app\admin\model\jdy\Maintenance;
        $where0 = "";
        $thismonth = date("Y-m");
        if ($mode == 0) {
            //一个月
            $fromdate = date("Y-m-d H:i:s", strtotime($thismonth));
            $where0 = "create_time > '". $fromdate."'";
        } else if ($mode == 1) {
            //三个月
            $fromdate = date("Y-m-d H:i:s", strtotime("-2 month", strtotime($thismonth)));
            $where0 = "create_time > '". $fromdate."'";
        } else if ($mode == 2) {
            //六个月
            $fromdate = date("Y-m-d H:i:s", strtotime("-5 month", strtotime($thismonth)));
            $where0 = "create_time > '". $fromdate."'";
        }

        if (!empty($keywords)) {
            if (!empty($where0)) {
                $where0 .= " and ";
            }
            $where0 .= "content like '%" . $keywords . "%' ";
        }

        $content0 = "<ul>";
        $list = $model
            ->where('anchang_id', $anchang_id)
            ->where($where0)
            ->field('id, task_id, content, message, switch, create_time, luruman')
            ->order("create_time desc")
            ->select();

        $maintenanceid = 0;
        $taskid = 0;
        foreach ($list as $row) {
            //？？？使用上一次的task_id？不懂就先去掉
            if ($maintenanceid == 0) {
//                $maintenanceid = $row['id'];
//                $taskid = $row['task_id'];
            }
            $message = "";
            if ($row->message) {
                $message = $row->message;
            }

            $content0 .= "<li>".$row->create_time . "<br>录入人員:" .$row->luruman. "<br>内容:" . $row->content . "<br>主管留言:" . $message . "</li>";
        }

        $content0 .= "</ul>";

        $this->view->assign("maintenanceid", $maintenanceid);
        $this->view->assign("taskid", $taskid);

        return $content0;
    }

    public function kssg()
    {
        if (!$this->dotask("未完工")) {
            $this->error("错误的工作事项！");
        }

        $this->success("已開始施工！");

    }

    public function jiean() {

        if (!$this->dotask("已結案")) {
            $this->error("错误的工作事项！");
        }
        $this->success("已結案！", url('home/index'));
    }

    public function dbj() {

        if (!$this->dotask("待報價")) {
            $this->error("错误的工作事项！");
        }
        $this->success("待報價！", url('home/index'));
    }

    public function dqk() {

        if (!$this->dotask("待請款")) {
            $this->error("错误的工作事项！");
        }
        $this->success("待請款！", url('home/index'));
    }

    public function hxsg() {

        if (!$this->dotask("未完工")) {
            $this->error("错误的工作事项！");
        }
        $this->success("後續施工！", url('home/index'));
    }

    function dotask($task_status)
    {
        $lng = $this->request->request("lng", "");
        $lat = $this->request->request("lat", "");
        $task_id = $this->request->request("task_id", 0);

        $task = \app\admin\model\jdy\Task::get($task_id);
        if (!$task) {
            $this->error("错误的工作事项！");
            return false;
        }
        $task->task_status = $task_status;
        $task->save();

        $tpos = new \app\admin\model\jdy\Taskposition();
        $tpos->task_id = intval($task_id);
        $tpos->lng = $lng;
        $tpos->lat = $lat;
        $tpos->task_status = $task_status;
        $tpos->luruman = $this->adminuser->nickname;
        $tpos->save();

        return true;
    }

    public function bjdqr() {

        if (!$this->dotask("待備料")) {
            $this->error("错误的工作事项！");
        }
        $this->success("已報價單簽認！");
    }

//    public function sgwb() {
//
//        if (!$this->dotask("待請款")) {
//            $this->error("错误的工作事项！");
//        }
//        $this->success("已施工完畢！");
//    }

    public function qkdsd() {

        if (!$this->dotask("已出單")) {
            $this->error("错误的工作事项！");
        }
        $this->success("請款單送達！");
    }

    public function cxselect()
    {
        $type = $this->request->get('type', '');
        $xianshi = $this->request->get('xianshi', '');

        $list = null;
        if ($type == 'xianshi') {
            $sql = "select name as value, name from city WHERE 1";
            $list = Db::query($sql);
        } else if ($xianshi !== '') {
            $sql = "select t.name as value, t.name as name from town t INNER JOIN city c on t.city_code=c.code WHERE c.name= '" . $xianshi . "'";
            $list = Db::query($sql);
        }

        $this->success('', null, $list);
    }

}
